package com.graduation.clientback.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.graduation.clientback.common.R;
import com.graduation.clientback.domain.TbUser;
import com.graduation.clientback.service.TbUserService;
import com.graduation.clientback.utils.JwtUtil;
import com.graduation.clientback.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/tbUser")
public class TbUserController {

    @Autowired
    private TbUserService tbUserService;

    /**
     * 用户登录
     * @param userCode 用户编号
     * @param userPwd 用户密码
     * @return token
     */
    @PostMapping("/login")
    public R<String> login(String userCode, String userPwd){
        LambdaQueryWrapper<TbUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TbUser::getUserCode, userCode);
        TbUser user = tbUserService.getOne(queryWrapper);
        if(user == null) {
            return R.error("用户名不存在");
        }
        if(!user.getUserPwd().equals(userPwd)) {
            return R.error("密码错误");
        }
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getUserId());
        claims.put("code", user.getUserCode());
        return R.success(JwtUtil.genToken(claims));
    }

    /**
     * 获取个人信息
     * @return
     */
    @GetMapping("/profile")
    public R<TbUser> profile(){
        Map<String, Object> claims = ThreadLocalUtil.get();
        String userCode = (String) claims.get("code");
        LambdaQueryWrapper<TbUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TbUser::getUserCode, userCode);
        return R.success(tbUserService.getOne(queryWrapper));
    }

    /**
     * 修改个人信息
     * @return
     */
    @PutMapping("/update")
    public R<String> update(@RequestBody TbUser tbUser){
        tbUserService.updateById(tbUser);
        return R.success("修改成功");
    }

    /**
     * 修改密码
     */
    @PutMapping("/updatePwd")
    public R<String> updatePwd(String oldPassword, String password){
        Map<String, Object> claims = ThreadLocalUtil.get();
        String userCode = (String) claims.get("code");
        LambdaQueryWrapper<TbUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TbUser::getUserCode, userCode);
        TbUser user = tbUserService.getOne(queryWrapper);
        if(!user.getUserPwd().equals(oldPassword)){
           return R.error("旧密码错误");
        }
        user.setUserPwd(password);
        tbUserService.updateById(user);
        return R.success("修改成功");
    }
}
